package com.atguigu.web;

import com.atguigu.pojo.Book;
import com.atguigu.pojo.Page;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClientBookServlet extends BaseServlet {
    private BookService bookService = new BookServiceImpl();

    /**
     * 分页的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数  pa'geNo pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //调用Bookservice中的 page（pageNo,pageSize）方法  返回Page对象
        Page<Book> page=bookService.page(pageNo,pageSize);
        //设置url请求地址
        page.setUrl("client/bookServlet?action=page");
        //保存Page对象到request域中
        req.setAttribute("page",page);
        //强求转发到 /pages/manager/book_manager.jsp
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
    /**
     * 求指定价格内的数据page
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数  pa'geNo pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min=WebUtils.parseInt(req.getParameter("min"),0);
        int max=WebUtils.parseInt(req.getParameter("max"),Integer.MAX_VALUE);
        //调用Bookservice中的 page（pageNo,pageSize）方法  返回Page对象
        Page<Book> page=bookService.pageByPrice(pageNo,pageSize,min,max);
        //设置url请求地址
        //由于分完页之后   点击其他页  则不包含  min max参数  的bug
        StringBuilder sb=new StringBuilder("client/bookServlet?action=pageByPrice");
        //如果你有min和max请求参数追加到分页条的地址中
        if(req.getParameter("min")!=null){
            sb.append("&min=").append(req.getParameter("min"));
        }if(req.getParameter("max")!=null){
            sb.append("&max=").append(req.getParameter("max"));
        }
        page.setUrl(sb.toString());
        //保存Page对象到request域中
        req.setAttribute("page",page);
        //强求转发到 /pages/manager/book_manager.jsp
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
}
